<template>
  <el-dialog v-model="dialog" title="健康证" width="700px">
    <div style="max-height: 400px; overflow-y: auto; display: flex; justify-content: center;">
      <el-form ref="elForm" :model="form" style="width: 630px;">
        <el-form-item>
          <el-upload action="/v2/consumer/img" :file-list="fileList"
            :on-success="uploadSuccess"
            :on-remove="removeSuccess"
            accept=".jpg,.jpeg,.png" multiple
            :http-request="$upload" list-type="picture-card">
            <el-icon><plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button type="primary" @click="confirmUpdate">保存</el-button>
      <el-button @click="dialog = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
  
  import {
    ref,
    reactive,
    inject
  } from 'vue'
  import {
    Plus
  } from '@element-plus/icons-vue'
  
  const $message = inject('$message');
  const $post = inject('$post');
  const $upload = inject('$upload');
  
  const dialog = ref(false);
  
  const form = reactive({
    guid: '',
    type: 'buyer',
    img: [],
    imgDelete: []
  })
  
  const fileList = ref([]);
  
  // 上传成功
  const uploadSuccess = (res, file) => {
    file.id = res.data;
    file.flag = 1;
    form.img.push(res.data);
  }
  
  // 移除成功
  const removeSuccess = file => {
    if (file.flag == 0) {
      form.imgDelete.push(file.id);
    }
    form.img = form.img.filter(id => file.id != id);
  }
  
  // 确认保存
  const confirmUpdate = () => {
    form.img = form.img.join(',');
    form.imgDelete = form.imgDelete.join(',');
    $post('/consumer/editHealImg', form).then(res => {
      $message.success('修改成功');
      dialog.value = false;
      fileList.value = [];
    })
  }
  
  defineExpose({
    // 展示模态框
    show: guid => {
      dialog.value = true;
      $post('/v2/consumer/addHealthInit', {
        guid,
        type: 'buyer'
      }).then(res => {
        form.guid = guid;
        if (form.img) {
          form.img = res.data.img.split(',');
        } else {
          form.img = [];
        }
        form.imgDelete = [];
        if (res.data.imgs) {
          fileList.value = res.data.imgs.split(',').map(url => {
            return {
              url,
              id: url.replace(res.data.path, ''),
              // 0代表是已经存在的照片，1是新照片
              flag: 0
            }
          })
        } else {
          fileList.value = [];
        }
        
      })
    }
  })
  
</script>

<style>
</style>
